package com.jinlejia.erp.ui.house.prospect;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.jinlejia.erp.R;
import com.jinlejia.erp.bean.SearchRentCoreBean;
import com.jinlejia.erp.bean.SearchShsCoreBean;
import com.jinlejia.erp.databinding.ActivitySeachCoreSellBinding;
import com.jinlejia.erp.ui.house.SearchCoreHistoryFragment;
import com.jinlejia.erp.utils.DbUtil;
import com.weight.CustomToast;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;

/**
 * @author SongJiaTai
 * @description:出售查询核心
 * @date :2019/7/9 18:42
 */
public class SearchCoreSellActivity extends AppCompatActivity implements SeachCoreSellListFragment.CallBackValue {

    SeachCoreSellListFragment listFragment;
    SearchCoreHistoryFragment historyFragment;
    private int current = 0;
    private boolean houseNameIsInput = false;
    private boolean buildIsInput = false;
    private boolean unitIsInput = false;
    private boolean isbuild = true; //用于回显楼栋号列表

    private ActivitySeachCoreSellBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_seach_core_sell);
        initEvent();
        binding.backBtn.setOnClickListener(this::onViewClicked);
        binding.searchButton.setOnClickListener(this::onViewClicked);
        listFragment = new SeachCoreSellListFragment();
        historyFragment = SearchCoreHistoryFragment.newInstance(getIntent().getStringExtra("type"));
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.frame_layout, historyFragment);
        ft.commitAllowingStateLoss();

        //监听软键盘回车事件
        binding.houseName.setOnEditorActionListener((arg0, arg1, arg2) -> {
            if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
                if (getIntent().getStringExtra("type").equals("shs")){
                    EventBus.getDefault().post(arg0.getText().toString(), "TAG_SEARCH_SHS");
                }else{
                    EventBus.getDefault().post(arg0.getText().toString(), "TAG_SEARCH_RENT");
                }

                finish();
            }
            return false;
        });

        String easte = getIntent().getStringExtra("easte");
        String easteCode = getIntent().getStringExtra("easteCode");
        if (!TextUtils.isEmpty(easte) && !TextUtils.isEmpty(easteCode)) {
            isbuild = false;
            houseNameIsInput = true;
            binding.houseName.setText(easte);
            binding.houseName.setTag(easteCode);
            binding.noBuilding.setFocusable(true);
            binding.noBuilding.setFocusableInTouchMode(true);
            binding.noBuilding.requestFocus();
            FragmentManager fm1 = getSupportFragmentManager();
            FragmentTransaction ft1 = fm1.beginTransaction();
            ft1.replace(R.id.frame_layout, listFragment);
            ft1.commitAllowingStateLoss();
            listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_BUILDING, easteCode, binding.noBuilding.getText().toString());
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEvent() {
        binding.houseName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onHouseNameTextChange(s, start, before, count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isbuild) {
                    onAfterTextChanged(s);
                } else {
                    isbuild = true;
                }

            }
        });
        binding.noBuilding.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onBuildTextChange(s, start, before, count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                buildingTextChanged(s);
            }
        });
        binding.noUnit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onUnitTextChange(s, start, before, count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                unitTextChanged(s);
            }
        });
        binding.noRoom.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                onRoomTextChange(s, start, before, count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                roomTextChanged(s);
            }
        });
        binding.noBuilding.setOnTouchListener((v, event) -> touch(v));
        binding.noUnit.setOnTouchListener((v, event) -> touch(v));
        binding.noRoom.setOnTouchListener((v, event) -> touch(v));
    }


    // region OnTextChanged事件
    /*
     当EditText触发OnTextChanged事件后，将后续牵连的EditText Text,Tag进行清空
     ，并且将当前EditText的Tag置为null
     */
    void onHouseNameTextChange(CharSequence s, int start, int before, int count) {

        houseNameIsInput = false;

        binding.houseName.setTag(null);
        binding.noUnit.setText(null);
        binding.noUnit.setTag(null);
        binding.noBuilding.setText(null);
        binding.noBuilding.setTag(null);
        binding.noRoom.setText(null);
        binding.noRoom.setTag(null);
    }

    void onBuildTextChange(CharSequence s, int start, int before, int count) {
        buildIsInput = false;

        binding.noBuilding.setTag(null);
        binding.noUnit.setText(null);
        binding.noUnit.setTag(null);
        binding.noRoom.setText(null);
        binding.noRoom.setTag(null);
    }


    void onUnitTextChange(CharSequence s, int start, int before, int count) {
        unitIsInput = false;

        binding.noUnit.setTag(null);
        binding.noRoom.setText(null);
        binding.noRoom.setTag(null);
    }

    void onRoomTextChange(CharSequence s, int start, int before, int count) {
        binding.noRoom.setTag(null);
    }
    //endregion

    private void replaceFragment(Editable s) {
        if (s.length() > 0 && current == 0) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.frame_layout, listFragment);
            ft.commitAllowingStateLoss();
            current = 1;
        }
        if (s.length() == 0 && current == 1) {
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.commitAllowingStateLoss();
            current = 0;
        }
    }
    //region OnTextChanged#AFTER_TEXT_CHANGED 事件触发
    /*
      当EditText文本内容改变时，进行查询相关数据
     */

    void onAfterTextChanged(Editable s) {
        replaceFragment(s);
        if (s.length() > 0)
            listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_NAME, s.toString());
    }


    void buildingTextChanged(Editable s) {
        replaceFragment(s);
        if (s.length() > 0)
            listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_BUILDING, String.valueOf(binding.houseName.getTag()), s.toString());
    }


    void unitTextChanged(Editable s) {
        replaceFragment(s);
        if (s.length() > 0)
            listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_UNIT, String.valueOf(binding.noBuilding.getTag()), s.toString());
    }


    void roomTextChanged(Editable s) {
        replaceFragment(s);
        if (s.length() > 0)
            listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_ROOM, String.valueOf(binding.noUnit.getTag()), s.toString());
    }
    //endregion

    //当EditText点击时，并且前置数据不合法时，直接拦截touch事件

    public boolean touch(View view) {
        switch (view.getId()) {
            case R.id.no_building: //座栋号
                if (TextUtils.isEmpty(binding.houseName.getText()) || !houseNameIsInput) {
                    CustomToast.showToast(SearchCoreSellActivity.this, "请先选择楼盘", 1500);
                    return true;
                } else {
                    listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_BUILDING, String.valueOf(binding.houseName.getTag()), binding.noBuilding.getText().toString());
                }
                break;
            case R.id.no_unit: //单元号
                if (TextUtils.isEmpty(binding.noBuilding.getText()) || !buildIsInput) {
                    CustomToast.showToast(SearchCoreSellActivity.this, "请先选择楼栋号", 1500);
                    return true;
                } else {
                    listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_UNIT, String.valueOf(binding.noBuilding.getTag()), binding.noUnit.getText().toString());
                }
                break;
            case R.id.no_room: //房间号
                if (TextUtils.isEmpty(binding.noUnit.getText()) || !unitIsInput) {
                    CustomToast.showToast(SearchCoreSellActivity.this, "请先选择单元号", 1500);
                    return true;
                } else {
                    listFragment.inputText(SeachCoreSellListFragment.TYPE_HOUSE_ROOM, String.valueOf(binding.noUnit.getTag()), binding.noRoom.getText().toString());
                }
                break;
        }
        return false;
    }

    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.search_button:
                if (TextUtils.isEmpty(binding.houseName.getText().toString())
                        && TextUtils.isEmpty(binding.noBuilding.getText().toString())
                        && TextUtils.isEmpty(binding.noUnit.getText().toString())
                        && TextUtils.isEmpty(binding.noRoom.getText().toString())) {
                    CustomToast.showToast(SearchCoreSellActivity.this, "请输入搜索信息", 1500);
                } else {
                    SearchShsCoreBean bean = new SearchShsCoreBean();
                    SearchRentCoreBean bean1 = new SearchRentCoreBean();
                    if (TextUtils.isEmpty(binding.houseName.getText())) {
                        CustomToast.showToast(SearchCoreSellActivity.this, "请选择楼盘", 1500);
                        return;
                    } else {
                        bean.setEaste(binding.houseName.getText().toString());
                        bean1.setEaste(binding.houseName.getText().toString());
                        if (binding.houseName.getTag() != null){
                            bean.setEasteCode(binding.houseName.getTag().toString());
                            bean1.setEasteCode(binding.houseName.getTag().toString());
                        }

                    }

                    if (!TextUtils.isEmpty(binding.noBuilding.getText()) && binding.noBuilding.getTag() != null) {
                        bean.setBuildingNo(binding.noBuilding.getText().toString());
                        bean1.setBuildingNo(binding.noBuilding.getText().toString());
                    } else if (!TextUtils.isEmpty(binding.noBuilding.getText())) {
                        CustomToast.showToast(SearchCoreSellActivity.this, "请选择楼栋号", 1500);
                        return;
                    }
                    if (!TextUtils.isEmpty(binding.noUnit.getText()) && binding.noUnit.getTag() != null) {
                        bean.setUnitNo(binding.noUnit.getText().toString());
                        bean1.setUnitNo(binding.noUnit.getText().toString());
                    } else if (!TextUtils.isEmpty(binding.noUnit.getText())) {
                        CustomToast.showToast(SearchCoreSellActivity.this, "请选择单元号", 1500);
                        return;
                    }
                    if (!TextUtils.isEmpty(binding.noRoom.getText()) && binding.noRoom.getTag() != null) {
                        bean.setRoomNo(binding.noRoom.getText().toString());
                        bean1.setRoomNo(binding.noRoom.getText().toString());
                    } else if (!TextUtils.isEmpty(binding.noRoom.getText())) {
                        CustomToast.showToast(SearchCoreSellActivity.this, "请选择房间号", 1500);
                        return;
                    }
                    if (getIntent().getStringExtra("type").equals("shs")){
                        saveShsHistory(bean);
                    }else{
                        saveRentHistory(bean1);
                    }

                }
                break;

            default:
                break;
        }
    }

    //region 点击选择的数据进行确定选择
    @Override
    public void houseNameValue(String strValue, String code) {
        binding.houseName.setText(strValue);
        binding.houseName.setTag(code);
        houseNameIsInput = true;
    }

    @Override
    public void houseBuildValue(String value, String code) {
        binding.noBuilding.setText(value);
        binding.noBuilding.setTag(code);
        buildIsInput = true;
    }

    @Override
    public void houseUnitValue(String value, String code) {
        binding.noUnit.setText(value);
        binding.noUnit.setTag(code);
        unitIsInput = true;
    }

    @Override
    public void houseRoomValue(String value, String code) {
        binding.noRoom.setText(value);
        binding.noRoom.setTag(code);
    }
    //endregion

    //region 保存出售历史记录 按照ID进行倒叙
    public void saveShsHistory(SearchShsCoreBean bean) {
        ArrayList<SearchShsCoreBean> shsList = DbUtil.getDB(this).single().query(SearchShsCoreBean.class);
        for (SearchShsCoreBean b : shsList) {
            if (TextUtils.equals(String.valueOf(b), String.valueOf(bean))) {
                //已经有当前记录
                DbUtil.getDB(this).single().delete(b);
                break;
            }
        }
        if (shsList.size() == 20) {
            //已经有20个记录，删除第一个
            DbUtil.getDB(this).single().delete(shsList.get(0));
        }
        DbUtil.getDB(this).save(bean);
        EventBus.getDefault().post(bean, "TAG_SEARCH_SHS_HISTORY");
        Intent intent = new Intent();
        intent.putExtra("easte", bean.getEaste());
        intent.putExtra("easteCode", bean.getEasteCode());
        setResult(RESULT_OK, intent);
        finish();
    }

    //endregion

    //region 保存出租历史记录 按照ID进行倒叙
    public void saveRentHistory(SearchRentCoreBean bean) {
        ArrayList<SearchRentCoreBean> shsList = DbUtil.getDB(this).single().query(SearchRentCoreBean.class);
        for (SearchRentCoreBean b : shsList) {
            if (TextUtils.equals(String.valueOf(b), String.valueOf(bean))) {
                //已经有当前记录
                DbUtil.getDB(this).single().delete(b);
                break;
            }
        }
        if (shsList.size() == 20) {
            //已经有20个记录，删除第一个
            DbUtil.getDB(this).single().delete(shsList.get(0));
        }
        DbUtil.getDB(this).save(bean);
        EventBus.getDefault().post(bean, "TAG_SEARCH_RENT_HISTORY");
        Intent intent = new Intent();
        intent.putExtra("easte", bean.getEaste());
        intent.putExtra("easteCode", bean.getEasteCode());
        setResult(RESULT_OK, intent);
        finish();
    }

    //endregion
}
